package org.netty.framework.httpserver.http;

import java.nio.charset.Charset;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

/**
 * http response,设置响应内容和响应头
 * 
 * @author chenfanglin
 * @date 2018年9月20日下午5:18:40
 *
 */
public class HttpServerResponse extends DefaultFullHttpResponse {

	private int contentLength;

	private volatile boolean contentSetted = false;

	public HttpServerResponse() {
		// 初始化一些默认值
		super(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	}

	public void setContent(String result) {
		super.setContent(Unpooled.wrappedBuffer(result.getBytes(CharsetUtil.UTF_8)));
		contentLength = content().readableBytes();
		contentSetted = true;
	}

	/**
	 * 302重定向
	 * 
	 * @param localtionUrl
	 *            重定向的URL
	 */
	public void redirect(String localtionUrl) {
		setStatus(HttpResponseStatus.FOUND);
		setHeaderIfEmpty(HttpHeaderNames.LOCATION.toString(), localtionUrl);
	}

	/**
	 * 重定向
	 * 
	 * @param localtionUrl
	 *            重定向的URL
	 */
	public void redirect(String localtionUrl, HttpResponseStatus status) {
		setStatus(status);
		setHeaderIfEmpty(HttpHeaderNames.LOCATION.toString(), localtionUrl);
	}

	public Charset getResponseCharset() {
		return CharsetUtil.UTF_8;
	}

	public long getContentLength() {
		return contentLength;
	}

	public boolean getContentSetted() {
		return contentSetted;
	}

	public boolean setHeaderIfEmpty(String name, String value) {
		if (headers().get(name) == null) {
			headers().set(name, value);
			return true;
		}
		return false;
	}
}
